package com.bsj.travel.common;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bsj.travel.def.common.DO.UserDO;
import com.bsj.travel.mapper.mysql.UserMapper;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/***
 * @description 用户通用
 * @author LiJiaXin
 * @version 1.0.0
 * @time 2023/5/26 17:17
 **/
@Component
public class UserCommon {

    @Resource
    private UserMapper userMapper;

    /**
     * 获取当前用户的所有下级或上级用户id（包括本身）
     *
     * @param userId
     * @param type   1:上级 2:下级
     * @return java.util.List<java.lang.Integer>
     * @author ljx
     * @time 2023/5/26 17:18
     */
    public List<Integer> getUserIds(Integer userId, Integer type) {
        Set<Integer> set = new HashSet<>();
        //需要查询的下级id
        Set<Integer> userIds = new HashSet<>() {
            {
                add(userId);
                set.add(userId);
            }
        };
        if (type == 1) {
            getSuUId(set, userIds);
        } else {
            getLoUId(set, userIds);
        }
        return set.stream().collect(Collectors.toList());
    }

    /**
     * 获取下级用户id
     *
     * @param set
     * @param userIds
     * @return void
     * @author ljx
     * @time 2023/5/26 17:18
     */
    private void getLoUId(Set<Integer> set, Set<Integer> userIds) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("parentId", userIds);
        queryWrapper.select("userId");
        List<UserDO> userList = userMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(userList)) {
            userIds.clear();
            for (UserDO user : userList) {
                Integer userId = user.getUserId();
                set.add(userId);
                userIds.add(userId);
            }
            getLoUId(set, userIds);
        }
    }

    /**
     * 获取上级用户id
     *
     * @param set
     * @param userIds
     * @return void
     * @author ljx
     * @time 2023/5/26 17:19
     */
    private void getSuUId(Set<Integer> set, Set<Integer> userIds) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("userId", userIds);
        queryWrapper.select("parentId");
        List<UserDO> userList = userMapper.selectList(queryWrapper);
        List<Integer> userIdList = userList.stream().map(UserDO::getParentId).collect(Collectors.toList());
        userIdList.remove(new Integer(-1));
        if (!CollectionUtils.isEmpty(userIdList)) {
            userIds.clear();
            for (Integer userId : userIdList) {
                set.add(userId);
                userIds.add(userId);
            }
            getSuUId(set, userIds);
        }
    }


}
